#coding:utf-8
"""
*   TG_Coder : Dzlua
*   Email    : 505544956@qq.com
*   Time     : 2017/08/16
"""

import MySQLdb
import re

class DataBase:
    def __init__(self, host, user, pwd, db):
        self.tb = self.__class__.__name__.lower()
        self.__db = MySQLdb.connect(host=host,user=user,passwd=pwd,db=db,charset="utf8")
        print('[database] open mysql ok. host: %s, user: %s, db: %s' % (host, user, db))
        self.__dbname = db
    def close(self):
        self.__db.close()
        print('[database] mysql closed. db: %s' % (self.__dbname))
    def execute(self, sql, param=None):
        cursor = self.__db.cursor()
        if param:
            cursor.execute(sql, param)
        else:
            cursor.execute(sql)
        cursor.close()
        self.__db.commit()
    def select(self, sql, param=None):
        cursor = self.__db.cursor()
        if param:
            cursor.execute(sql, param)
        else:
            cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        return result
    def save(self, fun_save, data, args = None):
        return fun_save(self.__db, data, args)
    def read(self, fun_read, args = None):
        return fun_read(self.__db, args)
    def to_binary(self, data):
        return MySQLdb.Binary(data)
    def strip(self, text):
        return re.sub(r'\s+','', text)